<script lang="ts" setup>
import Header from "@/components/author/Header.vue";
import {publishBook, register} from "@/api/author";
import {onMounted, reactive, ref, toRefs} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, type FormInstance} from "element-plus";
import {listCategorys} from "@/api/book";
import type {Book, BookCategory} from "@/type/book";
import picUpload from "@/assets/images/pic_upload.png";

const route = useRoute();
const router = useRouter();
const bookFormRef = ref()
const state = reactive({
  isLoading: false,
  book: {workDirection: 0, isVip: 0} as Book,
  bookCategorys: [] as BookCategory[],
  rules: {
    bookName: [
      {required: true, message: '小说名不能为空', trigger: 'blur'},
      {pattern: /^[^ ]+$/, message: '小说名不允许有空格', trigger: 'blur'},
      {max: 50, message: '小说名长度不能超过50个字符', trigger: 'blur'},
    ],
    categoryId: [{required: true, message: '分类不能为空', trigger: 'change'}],
    workDirection: [{required: true, message: '作品方向不能为空', trigger: 'change'}],
    bookDesc: [{required: true, message: '小说介绍不能为空', trigger: 'blur'}],
    picUrl: [{required: true, message: '封面不能为空', trigger: 'change'}],
  },
  baseUrl: import.meta.env.VITE_APP_BASE_API_URL,
  imgBaseUrl: import.meta.env.VITE_APP_BASE_IMG_URL

})
const {book, rules, bookCategorys, baseUrl, imgBaseUrl, isLoading} = toRefs(state)
onMounted(() => {
  loadCategoryList()
})

const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("必须上传 JPG 格式的图片!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小最多 5MB!");
    return false;
  }
  return true;
};

const handleAvatarSuccess = (response: any, uploadFile: any) => {
  state.book.picUrl = response.data;
};

const loadCategoryList = async () => {
  const {data} = await listCategorys({workDirection: state.book.workDirection});
  state.book.categoryId = data[0].id
  state.book.categoryName = data[0].name
  state.bookCategorys = data;
};

const categoryChange = async (event: any) => {
  console.log("categoryChange======", event.target.value)
  state.bookCategorys.forEach((category) => {
    if (category.id == event.target.value) {
      state.book.categoryName = category.name
      return
    }
  });
}

const saveBook = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      try {
        await publishBook(state.book)
        ElMessage.success("小说创建成功!");
        router.push({'name': 'authorBookList'})
      } catch (error) {

      }
      isLoading.value = false;
    } else {
      console.log('error submit!')
      return false
    }
  })
};
</script>
<template>
  <div class="main">
    <div class="container">
      <div class="top">
        <Header></Header>
      </div>
      <div class="bottom">
        <div class="left">
          <div>
            <RouterLink :to="{'name':'authorBookList'}" class="nav">小说管理</RouterLink>
          </div>
        </div>
        <div class="right">
          <div class="create-book">
            <div class="title">小说基本信息填写</div>
            <div class="form">
              <el-form ref="bookFormRef" :model="book" :rules="rules" label-width="100px">
                <el-form-item label="作品方向" prop="workDirection">
                  <el-select v-model="book.workDirection" placeholder="请选择作品方向" @change="loadCategoryList()">
                    <el-option :value="0" label="男频">男频</el-option>
                    <el-option :value="1" label="女频">女频</el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="分类" prop="categoryId">
                  <el-select v-model="book.categoryId" placeholder="请选择作品分类" @change="categoryChange">
                    <el-option
                        v-for="item in bookCategorys"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="小说名" prop="bookName">
                  <el-input v-model="book.bookName" maxlength="50" placeholder="请输入小说名" type="text"></el-input>
                </el-form-item>
                <el-form-item label="小说封面" prop="picUrl">
                  <el-upload
                      :action="baseUrl + '/front/resource/image'"
                      :before-upload="beforeAvatarUpload"
                      :on-success="handleAvatarSuccess"
                      :show-file-list="false"
                      class="avatar-uploader"
                  >
                    <img
                        :src="
                          book.picUrl ? imgBaseUrl + book.picUrl : picUpload
                        "
                        class="avatar"
                    />
                  </el-upload>
                </el-form-item>
                <el-form-item label="小说介绍" prop="bookDesc">
                  <el-input v-model="book.bookDesc" :rows="10" class="book-desc" maxlength="2000"
                            placeholder="请输入小说介绍" type="textarea"></el-input>
                </el-form-item>
              </el-form>
              <div>
                <el-button :loading="isLoading" round @click="saveBook(bookFormRef)">提交</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.main {
  background-color: #F5F5F5;
  padding: 20px;

  .container {
    width: 60%;
    background-color: #fff;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 10px;

    .bottom {
      display: flex;
      //height: 80vh;
      .left {
        flex: 1;
        padding: 10px 0;

        div {
          padding: 10px;
          width: 80%;
          text-align: center;
          border-left: 5px solid #48A4FF;
          background-color: #F5F5F5;

          a {
            text-decoration: none;
          }
        }

        border-right: 2px solid #F5F5F5;
      }

      .right {
        flex: 3;
        padding: 10px;

        .create-book {
          .title {
            font-size: 25px;
          }

          display: flex;
          gap: 30px;
          flex-direction: column;
          align-items: center;
          justify-content: center;

          .form {
            padding: 20px;
            border: 1px solid #F5F5F5;
            display: flex;
            flex-direction: column;
            text-align: center;
            justify-content: center;
            width: 80%;

            .el-form {
              margin: 0 auto;
              width: 60%;
            }

            .avatar-uploader {
              .avatar {
                display: block;
                box-sizing: border-box;
                border: 1px solid #000;
                object-fit: cover;
                width: 120px;
                height: 150px;
              }
            }

            .el-textarea {
              :deep(.el-textarea__inner) {
                height: 200px;
                resize: none;
              }
            }

            .el-button {
              width: 100px;
              background-color: #fc7403;
              color: #FFFFFF;
            }
          }
        }
      }
    }
  }
}
</style>